const app = getApp()
const globalData = app.globalData
const api = require('../../../api/index')
// 写死数据方便测试评论区
const testdata = require("testdata.js")
const utils = require('../../../utils/util')
const http=require('../../../utils/http')
const WxParse = require('../../../wxParse/wxParse')

Page({
    data: {
        // 拼团状态
        PTCode:"",
        //参团时间
        CreateTime:"",
        // 参团code
        CreateTimeCode:true,
        PTpage:1,
        PTpagesize:10,
        helpOrder:"",
        helpSpceId:"",
        helpKJCode:false,
        itemId:"",
        kanjiaText:"立即砍一刀",
        kanjiaCode:0,
        increase_amount:"",
        item:"",
        goodId:"",
        evaluateArr: [],
        source: '', // 场景来原 goods 普通商品 zaohui pingtuan miaosha kanjia 活动类型 
        pageNmae: '', // 页面来源 my 从我的模块过来的
        id: '', // 商品id/活动id 
        orderId: '', // 订单id  拼团/秒杀/砍价等当参与了活动进来的时候显示，当有拼团id时，显示拼团详情，立即参数直接参加这个拼团信息
        status: 0, // 商品状态
        countDown: { // 是否显示倒计时 pingtuan miaosha zaohui 需要
            show: false, // 是否显示
            timer: null, // 定时器指
            title: '距离秒杀结束', // 显示文本
            startTime: 0, // 开始时间
            endTime: 0, // 结束时间
            time: 0, // 时间
            timeArray: {}, // 时间数组
            funName: '' // 倒计时结束时，执行的函数名 this[funName] 进行调用
        },
        banner: {
            data: [],
            autoplay: true,
            interval: 3000,
            duration: 1000,
            currentSwiper: 0,
            carCount: 0,
            groupList: [], // 正在拼团的商品列表
        },
        isIpx: globalData.isIpx,
        imageBaseUri: globalData.imageBaseUri,
        pageData: {}, // 商品数据
        attention: '', // 富文本框
        cartCount: 0, // 购物车数量
        toast: {
            visible: false,
            text: ''
        },
        active: 0, // 当前选择的规格商品
        userId: '',
        share: {
            visible: false,
            data: {},
        },
        showBuy: false, // [规格弹窗]显示规格
        showBuyType: 'goods', // [规格弹窗]显示类型 cart 购物车 goods普通商品 activity活动商品
        showBuyData: {},
        onum: 1, // [规格弹窗]初始化数量
        buy: false,
        num: 1, // 购买数量初始化
        goodsInfo: { // 商品基础属性
            activityId: '', // id，用来下单使用
            activityIsBuy: true, // 活动是否可以下单，主要针对有限时的活动设置
            title: '', // 活动标题 / 商品标题
            price: '', // 商品价格，不同的活动商品，价格的来源不一样
            activityId: '', //活动id
        },
        miaosha: { // 秒杀额外参数
            data: {}
        },
        kanjia: { // 砍价额外参数
            data: {}
        },
        pingTuan: { // 拼团的额外参数
            order: { // [拼团订单数据]
                list: [], // 参团列表
                endTime: '', // 结束时间
                surplus: 0, // 还差几人成团
                isJoin: false, // 当前用户是否参加
                isMy: false, // 当前用户是否是团长
                isEnd: false, // 是否结束
                endTimeArray: {} // 结束倒计时
            },
            data: {},
            joinPropShow: false,
        },
        zaohui: { // 早惠额外参数
            data: {}
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

        console.log('商品详情页面', options)
        this.setData({
            goodId:options.id,
            item:options,
            id:options.id
        })
        // 分享者id
        if (options.userId) {
            console.log("来了吗");
            console.log(this.data.item)
            console.log(this.data.item.userId)
            wx.setStorageSync('superiorsID',this.data.item.userId)
            wx.setStorageSync('shareID', this.data.item.userId)
        }
        // 砍价订单页面   的邀请砍价
        if (options.source=='kanjia') {
            if (options.kanjiaCode) {
                this.setData({
                    kanjiaCode:1,
                    kanjiaText:"邀请好友砍一刀"
                })    
            }
            if (options.sharekanjiaID) {
                this.setData({
                    helpOrder:options.sharekanjiaID,
                    helpSpceId:options.KJ
                })
            }
        }
        // // 绑定上级关系

        // if (options.invitationId) {
        //     console.log(options.invitationId);
        //     wx.setStorageSync('superiorsID', options.invitationId)
        // }

        // 帮忙砍价
        if(options.shareCode){
            if (options.shareCode==0) {
                this.setData({
                    helpKJCode:true
                })
            }
        }
        let scene = options.scene || ''; // 通过什么方式打开小程度
        let userId = options.userId || ''; // 邀请人id

        let source = options.source || 'goods'; // 商品类型 -> 后面改为 goodsType
        let id = options.id || ''; // 活动id
        let goodsId = options.goodsId; // 商品id
    
        let orderId = options.orderId; // 订单id,当带有订单id时，要显示订单的相关信息
        let pageName = options.pageName || ''; // 来源页面 -> 后央改为 sourcePage
        
        // 通过分享进来的
        if (scene) {
            console.log(scene, 'scene')
            // scene 值是什么样的
            // '50024%262008291227289650512'
            if (scene.indexOf('&') != -1) {
                userId = scene.split('&')[0];
                id = scene.split('&')[1];
            } else {
                userId = scene.split('%26')[0];
                id = scene.split('%26')[1];
            }
        }

        this.setData({
            id,
            goodsId,
            userId,
            scene,
            source,
            pageName,
            orderId
        })
     
        // let user=wx.getStorageSync('userinfo')
        // if (user=="") {
        //     wx.showModal({
        //         showCancel:true,
        //         content: '请先登录哦!',
        //         success (res) {
        //           if (res.confirm) {
        //             wx.switchTab({
        //                 url: '/pages/mine/mine'
        //               })
        //           } 
        //         }
        //       })

        // }else{
            
        // }
        this.reload();
       
    },
    onShow: function () {
        // 处于打开状态下更新一次数据列表
        if (this.data.pingTuan.joinPropShow) this.pingtuanOrderList()
    },
    onHide() {
        this.countDownStop()
    },
    onUnload() {
        this.countDownStop()
    },
    onShareAppMessage: function (e) {
        console.log(e)
        let type = e.target.dataset.type
        let title, path, imageUrl;

        let {Id} =wx.getStorageSync('userinfo'); // 带有邀请人
        console.log(Id);
        let invitationId=wx.getStorageSync('superiorsID')
        console.log(invitationId, '打印的分享出去的id')

        if (type) {
            if (type === 'pingtuan') {
                // 拼团分享
                path = `/pages/product/detail/detail?id=${this.data.id}&orderId=${this.data.orderId}&source=pingtuan&userId=${Id}&isShare=true&invitationId=${invitationId}`
                console.log(path,"拼团分享");
            }
        }else{
            console.log(this.data.item.source);
            if (this.data.item.source=="miaosha") {
                path = `/pages/product/detail/detail?id=${this.data.id}&userId=${Id}&goods_id=${this.data.item.goodsId}&source=miaosha`
                console.log(path,"秒杀分享");
                //秒杀分享
            }if (this.data.item.source=="pingtuan") {
                //平团分享
                path = `/pages/product/detail/detail?id=${this.data.id}&orderId=${this.data.orderId}&source=pingtuan&userId=${Id}&isShare=true&invitationId=${invitationId}`
                console.log(path,"拼团分享");
            }  if (this.data.item.source=="zaohui") {
                path = `/pages/product/detail/detail?id=${this.data.id}&source=zaohui&userId=${Id}&invitationId=${invitationId}`
                console.log(path,"早慧分享");
                //早慧分享
            }else if (this.data.item.source=="kanjia") {
                  //砍价分享  
                  let {HeadIcon}=wx.getStorageSync('userinfo')
                  let {Id}=wx.getStorageSync('userinfo')
                  var sharekanjiaID=""
                  if (this.data.item.itemCode==0) {
                      console.log(1111);
                    sharekanjiaID=this.data.item.sharekanjiaID
                  }else{
                    console.log(2222);
                    sharekanjiaID=wx.getStorageSync(this.data.helpOrder)
                  }
                  
                  console.log(sharekanjiaID,this.data.helpOrder,55555555555);
                  path = `/pages/product/detail/detail?id=${this.data.goodId}&userId=${Id}&shareCode=0&helpMeImg=${HeadIcon}&sharekanjiaID=${sharekanjiaID}&source=kanjia&KJ=${this.data.helpSpceId}&invitationId=${invitationId}`
                  console.log(path,"分享链接");
             
            }else if(this.data.item.source==undefined){
                let {Id}=wx.getStorageSync('userinfo')
                 // 普通商品分享
            path = `/pages/product/detail/detail?id=${this.data.id}&userId=${Id}&goods_id=${this.data.item.id}&invitationId=${invitationId}`
            console.log(path,"普通分享");
            }
              
        }

        return {
            title: this.data.goodsInfo.title,
            path: path,
            imageUrl: this.data.pageData.GoodsFileDtos[0].FilePath
        }
    },
    methods:{
      
    },

   


    // 砍价组件穿过来的值
    KJ(e){
        console.log(e.detail);
        let item=e.detail
        let {Id}=wx.getStorageSync('userinfo')
        this.setData({
            kanjiaCode:e.detail.kanjiaCode,
            kanjiaText:e.detail.kanjiaText,
            itemId:e.detail.itemId||"",
            helpSpceId:e.detail.spec_id
        })
        if (this.data.itemId!=undefined) {
            let itemT=`${Id}_${item.spec_id}_${item.itemId}`
            console.log( itemT);
            // wx.setStorageSync('shareKJID', this.data.itemId)
            wx.setStorageSync(`${Id}_${item.spec_id}_${item.itemId}`,  this.data.itemId)
            this.setData({
                helpOrder:itemT
            })
            console.log(wx.getStorageSync((`${Id}_${item.spec_id}_${item.itemId}`)));
        }

         //砍价分享  
         let {HeadIcon}=wx.getStorageSync('userinfo')
        //  let {Id}=wx.getStorageSync('userinfo')
         var sharekanjiaID=wx.getStorageSync(this.data.helpOrder)
         let path = `/pages/product/detail/detail?id=${this.data.goodId}&userId=${Id}&shareCode=0&helpMeImg=${HeadIcon}&sharekanjiaID=${sharekanjiaID}&source=kanjia&KJ=${this.data.helpSpceId}`
         console.log(path,"分享链接");
         wx.setStorageSync('KjSharePath', path)
     
    },
    // 立刻砍一刀
    goKj(){
        console.log("立刻砍价");
        this.setData({
            showBuy: true,
            showBuyType: 'kanjia',
            showBuyData: {},
            onum: 1,
        })
    },
    // 分享砍价
    shareKJ(){
        console.log("分享砍价");
        this.showShare()
    },
    // 帮别人砍价
    helpKj(){
        let user=wx.getStorageSync("userinfo")
        if (user=="") {
            this. getUserProfile()
        }
        console.log("帮别人砍价",this.data.item);
    
        console.log(this.data.item.sharekanjiaID,1111);
        let obj={
            user_id:this.data.item.userId,
            id:this.data.item.sharekanjiaID,
            spec_id:this.data.item.KJ
        }
        console.log(obj);
        http.request("GET",'/bargain/user_bargain',obj).then((res)=>{
            console.log(res);
            if (res.data.ErrCode!=0) {
                wx.showModal({
                    content: res.data.ErrMsg,
                  })
            }else{
                wx.showModal({
                    content: `已砍下${res.data.ResData}元`,
                  })
            }
            this.setData({
                helpKJCode:false
            })
        })
    },
    // 登录
    getUserProfile() {
        let that = this
        // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
        // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
        wx.getUserProfile({
            desc: '用于下单购买商品', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: (res) => {
                console.log(res, '登录profile返回的res')
                let user = res.userInfo;
                that.setData({
                    phoneObjiv: res.iv,
                    phoneObjencryptedData: res.encryptedData
                })
                console.log(that.data.phoneObjiv, that.data.phoneObjencryptedData, "465656565");
                let obj = {
                    nickname: user.nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "*"),
                    province: user.province,
                    sex: user.gender,
                    city: user.city,
                    country: user.country,
                    headimgurl: user.avatarUrl,
                    unionid: '',
                    code: res.code || ''
                }
                console.log(obj);

                wx.login({
                    success: res => {
                        console.log('wx.login', res)
                        this.setData({
                            loading: true
                        })
                        try {
                            api.base.wxOnLogin(Object.assign(obj, {
                                code: res.code
                            })).then(res => {
                                console.log(res, '登录结果')
                                let token = res.data.ResData.AccessToken || '',
                                    userinfo = res.data.ResData || {};

                                // this.setData({
                                //   userInfo: res.data.ResData || {},
                                //   loading: false
                                // })

                                //token
                                wx.setStorageSync('token', token);
                                // app.globalData.authToken = token;

                                //存放用户信息
                                wx.setStorageSync('userinfo', userinfo);
                                app.globalData.userInfo = userinfo;

                                // 存放sessionId
                                wx.setStorageSync('ssId', userinfo.WxSessionId);
                                app.globalData.ssId = userinfo.WxSessionId;
                                that.setData({
                                    phoneType: true
                                })
                                this.reload();
                            })
                        } catch (e) {
                            this.setData({
                                loading: false
                            })
                        }
                    }
                })
            }
        })
    },
    /**
     * swiper切换
     */
    swiperChange(e) {
        this.setData({
            'banner.currentSwiper': e.detail.current
        })
    },
    linkTo(e) {
        let to = e.currentTarget.dataset.to;
        switch (to) {
            case '1':
                wx.reLaunch({
                    url: '/pages/index/index',
                })
                break;
            case '2':
                wx.reLaunch({
                    url: '/pages/car/car',
                })
                break;
            case '3':
                break;
            default:
                return;
        }
    },
    openPop(e) {
        console.log('openPop', e)
        let type=""
        
        if(e.currentTarget == undefined){
            type=e
        }else{
            type=e.currentTarget.dataset.type;
        }
        console.log(type);
    
        if (type === 'cart') {
            this.setData({
                showBuy: true,
                showBuyType: 'cart',
                showBuyData: {},
                onum: 1,
            })
        } else if (type === 'goods') {
            let showBuyType = this.data.source == 'goods' ? 'goods' :this.data.source == 'pingtuan' ?'goods': 'activity'
            this.setData({
                showBuy: true,
                showBuyType: showBuyType,
                showBuyData: {},
                onum: 1,
            })
        }
    },
    closePop(e) {
        this.setData({
            showBuy: false,
            showBuyData: {},
            num: 1,
        })
    },
    async reload() {
        console.log(this.data.source,"skikdfjgijriji");
        if (this.data.source === 'kanjia') {
            await this.kanjiaGoodsGet()
        } else if (this.data.source === 'miaosha') {
            await this.miaoshaGoodsDetails()
        } else if (this.data.source === 'pingtuan') {
            await this.pingtuanGoodsGet();
        } else if (this.data.source === 'zaohui') {
            await this.zaohuiGoodsGet();
        } else { // 普通商品
            await this.getGoodsDetail();
        }
  
        this.get_evaluate(); // 获取评论
        // this.getCartList(); // 获取购物车，以显示购物车个数，不需要了
    },
    
   

    // 获取普通商品详情
    async getGoodsDetail() {
        try {
            let res = await api.goods.goodsDetail({
                id: this.data.id,
                invitationId: this.data.userId
            });
            let data = res.data.ResData || {};
            let shareData = this.data.share.data;
           
            let goodsInfo = {
                activityId: data.Id,
                title: data.Title,
                SubTitle: data.SubTitle,
                price: data.Price,
                marketPrice: data.MarketPrice,
                VirtualSaleNun:data.VirtualSaleNun
            }
           

            shareData = Object.assign(shareData, {
                id: data.Id,
                name: data.Title,
                minPrice: data.isSeckill ? data.SeckillPric : data.Price,
                showMinPrice: data.MarketPrice,
                img: data.GoodsFileDtos ? (data.GoodsFileDtos[0].FilePath || '') : '',
                userId: wx.getStorageSync('userinfo').UserId || '',
                avatar: wx.getStorageSync('userinfo').HeadIcon || '',
                userName: wx.getStorageSync('userinfo').NickName || ''
            });

            this.setData({
                goodsInfo: goodsInfo,
                pageData: data,
                "banner.data": data.GoodsFileDtos || [],
                attention: data.Detail,
                status: 2,
                'share.data': shareData,
            })
            console.log("sku",this.data.pageData);
            console.log("普通分享数据",this.data.share.data);

            this.setImg();
            this.getActive();
        } catch (e) {
            console.log(e, '获取商品详情失败')
            this.setData({
                status: 1
            })
        }
    },

    // 秒杀商品
    async miaoshaGoodsDetails() {
        try {
            let res = await api.goods.getGoodsSkillDetails({
                skill_id: this.data.id,
                goods_id: this.data.goodsId||this.data.item.goods_id,
                invitationId: this.data.userId
            })
            let data = res.data.ResData || {}
            let pageData = res.data.ResData.GoodsDto || {}
            let shareData = this.data.share.data

            console.log(pageData, res.data.ResData.goodsDto)
            console.log(data,pageData,"商品详情");
            let goodsInfo = {
                activityId: data.Id,
                title: pageData.Title,
                price: pageData.Price,
                marketPrice: pageData.MarketPrice,
                VirtualSaleNun:data.GoodsDto.VirtualSaleNun
            }

            let countDown = {
                show: true,
                timer: null,
                title: '活动倒计时',
                startTime: utils.dateToTime(data.StartTime),
                endTime: utils.dateToTime(data.EndTime),
                time: 0,
                timeArray: {
                    hours: '00',
                    minutes: '00',
                    seconds: '00'
                }
            }
            console.log("分享data",data);
            shareData = Object.assign(shareData, {
                id: data.Id,
                name: data.Title,
                minPrice: data.GoodsDto.Price,
                showMinPrice: data.GoodsDto.MarketPrice,
                img: data.GoodsDto.GoodsFileDtos[0].FilePath,
                userId: wx.getStorageSync('userinfo').UserId || '',
                avatar: wx.getStorageSync('userinfo').HeadIcon || '',
                userName: wx.getStorageSync('userinfo').NickName || ''
            });

            this.setData({
                ['miaosha.data']: res.data.ResData,
                goodsInfo: goodsInfo,
                pageData: pageData,
                "banner.data": pageData.GoodsFileDtos || [],
                attention: pageData.Detail,
                status: 2,
                countDown: countDown,
                'share.data': shareData,
            })
            console.log("秒杀分享数据",this.data.share.data);

            this.setImg();
            this.getActive();
            this.countDownOpen();
        } catch (e) {
            this.setData({
                status: 1
            })
        }
    },

    // 砍价商品详情
    async kanjiaGoodsGet() {
        console.log(this.data.id,"652656565");
        try {
            let res = await api.bargain.getBargainDetails({
                id: this.data.id,
                invitationId: this.data.userId
            })
            let data = res.data.ResData || {}
            let pageData = res.data.ResData.goodsInfo || {}
            let shareData = this.data.share.data

            console.log(data,555555)
           
            let goodsInfo = {
                activityId: data.id, //活动id
                title: data.title,
                price: data.Price+".00",
                marketPrice: data.initial_amount,
                VirtualSaleNun:data.goodsInfo.VirtualSaleNun
            }

            let countDown = {
                show: true,
                timer: null,
                title: '距离结束',
                startTime: data.start_time,
                endTime: data.end_time,
                time: 0,
                timeArray: {
                    hours: '00',
                    minutes: '00',
                    seconds: '00'
                }
            }
            console.log("砍价data",data);
            shareData = Object.assign(shareData, {
                id: data.goods_id,
                name: data.goodsInfo.Title,
                minPrice: data.minimum_amount,
                showMinPrice:  data.goodsInfo.MarketPrice,
                img: data.goodsInfo.GoodsFileDtos[0].FilePath,
                userId: wx.getStorageSync('userinfo').UserId || '',
                avatar: wx.getStorageSync('userinfo').HeadIcon || '',
                userName: wx.getStorageSync('userinfo').NickName || ''
            });

            this.setData({
                status: 2,
                ['kanjia.data']: res.data.ResData,
                goodsInfo: goodsInfo,
                pageData: pageData,
                countDown: countDown,
                attention: pageData.Detail,
                "banner.data": pageData.GoodsFileDtos || [],
                'share.data': shareData,
             
            })
            console.log("砍价分享数据",this.data.share.data);

            this.setImg();
            this.getActive();
            this.countDownOpen()
        } catch (e) {
            console.log(e,"失败原因");
            this.setData({
                status: 1
            })
        }
    },

    // 早惠商品详情
    async zaohuiGoodsGet() {
        console.log('avatar', wx.getStorageSync('userinfo').HeadIcon)
        try {
            let res = await api.activity.details({
                id: this.data.id,
                invitationId: this.data.userId||this.data.item.invitationId
            })

            let data = res.data.ResData || {}
            let shareData = this.data.share.data
          
           console.log(data,333333,data.goodsInfo.GoodsSpecDtos[0].Price);
            let goodsInfo = {
                activityId: data.id,
                title: data.title,
                SubTitle: data.SubTitle,
                price: data.goodsInfo.GoodsSpecDtos[0].Price,
                VirtualSaleNun:data.goodsInfo.VirtualSaleNun
            }

            let countDown = {
                show: true,
                timer: null,
                title: '距离下次上涨',
                startTime: data.start_time,
                endTime: data.end_time,
                time: 0,
                timeArray: {
                    hours: '00',
                    minutes: '00',
                    seconds: '00'
                }
            }
            console.log("早慧data",data);
            shareData = Object.assign(shareData, {
                id: data.goodsInfo.Id,
                name:data.goodsInfo.Title,
                minPrice: data.goodsInfo.Price,
                showMinPrice:data.goodsInfo.MarketPrice,
                img: data.goodsInfo.GoodsFileDtos[0].FilePath,
                userId: wx.getStorageSync('userinfo').UserId || '',
                avatar: wx.getStorageSync('userinfo').HeadIcon || '',
                userName: wx.getStorageSync('userinfo').NickName || ''
            });

            this.setData({
                status: 2,
                ['zaohui.data']: data,
                goodsInfo: goodsInfo,
                pageData: data.goodsInfo,
                countDown: countDown,
                attention: data.Detail,
                "banner.data": data.goodsInfo.GoodsFileDtos || [],
                'share.data': shareData,
                increase_amount:data.increase_amount
            })
            console.log("早慧分享数据",this.data.share.data);
            console.log(this.data.zaohui,"565656565656995",this.data. goodsInfo);

            this.setImg();
            this.getActive();
            this.countDownOpen()
            // TODO 早慧商品分为 购买上涨 与 计时上涨
        } catch (e) {
            console.log(e, '获取商品详情失败')
            this.setData({
                status: 1
            })
        }
    },

    // 拼团详情
    async pingtuanGoodsGet() {
        try {
            let res = await api.collage.getCollageDetails({
                id: this.data.id,
                invitationId: this.data.userId
            })
            let data = res.data.ResData || {}
            let pageData = res.data.ResData.goodsDto || {}
            let shareData = this.data.share.data;
            console.log(data,5656);
            console.log(pageData.Price)
            let goodsInfo = {
                activityId: data.Id,
                title: pageData.Title,
                price: pageData.Price,
                marketPrice: pageData.MarketPrice,
                VirtualSaleNun:data.goodsDto.VirtualSaleNun
            }
            console.log("拼团data",data);
            shareData = Object.assign(shareData, {
                id: data.Id,
                name: data.goodsDto.Title,
                minPrice:data.goodsDto.Price,
                showMinPrice: data.goodsDto.MarketPrice,
                img: data.goodsDto.GoodsFileDtos[0].FilePath ,
                userId: wx.getStorageSync('userinfo').UserId || '',
                avatar: wx.getStorageSync('userinfo').HeadIcon || '',
                userName: wx.getStorageSync('userinfo').NickName || ''
            });

            this.setData({
                status: 2,
                ['pingTuan.data']: res.data.ResData,
                goodsInfo: goodsInfo,
                pageData: pageData,
                "banner.data": pageData.GoodsFileDtos || [],
                attention: pageData.Detail,
                'share.data': shareData,
            })
            console.log("拼团分享",this.data.share.data);
            console.log("拼团数据",res.data.ResData);

            this.setImg();
            this.getActive();
            this.pingtuanMyOrderDetails()
        } catch (e) {
            console.log(e, '获取商品详情失败')
            this.setData({
                status: 1
            })
        }
    },

    /**
     * 获取我拼当前团的信息
     * 显示我的信息或者显示邀请人的信息
     */
    async pingtuanMyOrderDetails() {
        let that=this
        if (this.data.orderId) {
            let UserId = wx.getStorageSync('userinfo').UserId || ''
            let res = await api.collage.userList({
                collage_order_id: this.data.orderId,
                OrderSpellId:this.data.item.OrderSpellId
            })

            let data = res.data.ResData;
            let isJoin = false
            let isMy = false
            let isEnd = false

            data.list = data.list.map((item, index) => {
                if (item.UserId == UserId) {
                    isJoin = true

                    if (item.is_head == true) {
                        isMy = true
                    }
                }

                return item
            })


            // for (let i = 0; i < data.surplus; i++) {
            //     data.list.push({
            //         "Id": "", //拼团明细记录id
            //         "UserId": "", //用户id
            //         "CreateTime": "", //拼团时间
            //         "Status": 2, //状态：(2:拼团中、3:拼团完成)
            //         "SponsorPric": "", //价格
            //         "NickName": null, //昵称
            //         "HeadIcon": null //头像
            //     })
            // }

            let endTime = utils.dateToTime(data.endTime)
            let currentTime = parseInt(new Date().getTime() / 1000)
            console.log(endTime,currentTime,"时间");
            if (currentTime > endTime) {
                isEnd = true
            }

            data.isJoin = isJoin
            data.isMy = isMy
            data.isEnd = isEnd
         
            data.endTimeArray = utils.numberToCountDown(endTime - currentTime, 30)
           
            this.setData({
                ['pingTuan.order']: data
            })
            console.log(this.data.pingTuan.order);
            //  判断拼团状态
            if (this.data.pingTuan.order.surplus==0) {
                this.setData({
                    CreateTimeCode:false
                })
            }else{
                this.setData({
                    CreateTimeCode:true
                })
            }
            // 拿开团时间 
            let {Id}=wx.getStorageSync('userinfo')
            this.data.pingTuan.order.list.forEach((item) => {
                if (item.UserId==Id) {
                    that.setData({
                        CreateTime:item.CreateTime
                    })
                }
            });
            // TODO 差一个拼团倒计时
            that.setData({
                "countDown.endTime":endTime
            })
            this.countDownOpen()


        }
    },
    // 获取拼团列表
    async pingtuanOrderList() {
        console.log(this.data.pageData, 'pagedata')
        let that=this
        try {
            let res = await api.collage.getCollageList({
                    collage_id: this.data.pingTuan.data.Id,
                    page:that.data.PTpage,
                    pagesize:that.data.PTpagesize
                }),
                data = res.data.ResData.Items || [];

            let time = parseInt(new Date().getTime() / 1000)
            data = data.map((item, index) => {
                item.endTime = utils.dateToTime(item.EndTime)
                item.countTime = item.endTime - time; // 如果倒计时就需要移到里面去
                item.countTimeArray = utils.numberToCountDown(item.countTime, 30)
                return item
            })

            this.setData({
                groupList: data
            });
        } catch (e) {
            console.log(e, '获取拼团列表失败')
        }
    },

    // [立即参团]打开所有团的面板
    pingtuanPropOpen(e) {
        console.log(e);
        this.pingtuanOrderList()
        this.setData({
            ['pingTuan.joinPropShow']: !this.data.pingTuan.joinPropShow
        })
        // wx.navigateTo({
        //   url: `/component/FriendsGroup/FriendsGroup?goodsId=${e.currentTarget.dataset.id}`,
        // })
    },
    //  [立即参团]关闭所有团的面板
    pingtuanPropClose() {
        this.setData({
            ['pingTuan.joinPropShow']: !this.data.pingTuan.joinPropShow
        })
    },
     // 我要开团
     openParty(){
        console.log("我要开团");
        this.setData({
            ['pingTuan.joinPropShow']: !this.data.pingTuan.joinPropShow
        })
        console.log(this.data.goods);
        this.openPop("goods")

        },
    // [立即参团]选择后->打开购买弹窗
    toGroupJoinShowBuy(e) {
        console.log(e)
        let info = e.detail
        let showBuyData;

        if (info && info.Id) {
            showBuyData = {
                'isJson': true,
                'orderId': info.Id
            }
        } else if (this.data.orderId) {
            showBuyData = {
                'isJson': true,
                'orderId': this.data.orderId
            }
        } else {
            showBuyData = {}
        }
        let showBuyType = ''
        e.type == 'toGroupDetail' ? showBuyType = 'toGroupDetail' : showBuyType = 'activity'
        this.setData({
            showBuy: true,
            showBuyType: showBuyType, // [规格弹窗]显示类型 cart 购物车 goods普通商品 activity活动商品
            showBuyData,
            ['pingTuan.joinPropShow']: false // 隐藏面板
        })
    },


    /* 倒计时模块 */
    countDownOpen() {
        this.countDownStop()

        console.log('开户定时任务', this.data.countDown)

        this.countDownContent()

        this.data.countDown.timer = setInterval(() => {
            // console.log('倒计时定时任务')
            this.countDownContent()
        }, 1000)
    },
    /* 倒计时模块 */
    countDownStop() {
        console.log('停止定时任务', this.data.countDown)
        if (this.data.countDown.timer) {
            clearInterval(this.data.countDown.timer)
            this.data.countDown.timer = null
        }
    },
    /* 倒计时模块 */
    countDownContent() {
        let endTime = this.data.countDown.endTime
        let countDownNumber = endTime - parseInt(new Date().getTime() / 1000)
        // console.log(countDownNumber);
        // console.log(utils)
        this.setData({
            ['countDown.time']: countDownNumber,
            ['countDown.timeArray']: utils.numberToCountDown(countDownNumber, 30)
        })
        // console.log(this.data.countDown.timeArray);
    },

    // 富文本显示

    setImg(){
        let that = this
        if(!that.data.attention){
            return
        }
        let attention = that.data.attention;
        console.log(attention)
        WxParse.wxParse('attention', 'html', attention,that, 5);
    },
    

    // setImg() {
    //     let that = this
    //     if (!that.data.attention) {
    //         return;
    //     }

    //     let result = that.data.attention;

    //     WxParse.wxParse('attention', 'html', result,that, 5);



    //     const regex = new RegExp('<p', 'gi');
    //     const regexDiv = new RegExp('<div', 'gi');
    //     if (regex.test(this.data.attention)) {
    //         result = result.replace(regex, `<p style="width:100%;word-break:break-all;margin:0;padding:0;line-height:26px;font-size:14px;color:#6B6E75;"`);

    //         let result2 = result;
    //         const regex2 = new RegExp('<img', 'gi');
    //         if (regex2.test(result)) {
    //             result2 = result2.replace(regex2, `<img style="width:100%;display:block;margin:0 auto;padding:0;"`);

    //             let result3 = result2;
    //             const regex3 = new RegExp('style=""', 'gi');
    //             if (regex3.test(result2)) {
    //                 result3 = result3.replace(regex3, `alt`);
    //                 this.setData({
    //                     attention: result3
    //                 })
    //             } else {
    //                 this.setData({
    //                     attention: result2
    //                 })
    //             }
    //         } else {
    //             this.setData({
    //                 attention: result
    //             })
    //         }
    //     } else if (regexDiv.test(this.data.attention)) {
    //         result = result.replace(regexDiv, `<div style="margin:0;padding:0;width:100%;line-height:26px;font-size:14px;color:#6B6E75;"`);

    //         let result2 = result;
    //         const regex2 = new RegExp('<img', 'gi');
    //         if (regex2.test(result)) {
    //             result2 = result2.replace(regex2, `<img style="width:100%;margin:0;padding:0;"`);

    //             let result3 = result2;
    //             const regex3 = new RegExp('style=""', 'gi');
    //             if (regex3.test(result2)) {
    //                 result3 = result3.replace(regex3, `alt`);
    //                 this.setData({
    //                     attention: result3
    //                 })
    //             } else {
    //                 this.setData({
    //                     attention: result2
    //                 })
    //             }
    //         } else {
    //             this.setData({
    //                 attention: result
    //             })
    //         }
    //     }

    //     // console.log(this.data.attention, 'attention')
    // },

    // 加入购物车
    async addToCar() {
        if (!utils.getLoginState()) {
            return utils.checkLoginState({
                routeUri: 3,
                uri: `/pages/product/detail/detail?id=${this.data.id}&userId=${this.data.userId}`
            });
        }
        let spec = this.data.pageData.GoodsSpecDtos,
            arr = [],
            obj = {
                id: spec[this.data.active].Id,
                userId: wx.getStorageSync('userinfo').UserId || '',
                goodsId: spec[this.data.active].GoodsId,
                num: 1
            }

        // if (wx.getStorageSync('cart')) {
        //     let storageCart = wx.getStorageSync('cart');
        //     arr = storageCart.push(obj);
        //     wx.setStorageSync('cart', arr);
        //     console.log(spec, 'spec', storageCart, arr)
        // } else {
        //     arr = arr.push(obj)
        //     wx.setStorageSync('cart', arr)
        // }

        arr.push(obj)

        try {
            let res = await api.cart.addCart(arr),
                data = res.data.ResData || {};
            console.log(res, '添加购物车');
            this.setData({
                toast: {
                    visible: true,
                    text: '加入购物车成功'
                },
                status: 2
            })
            // this.getCartList();
        } catch (e) {
            console.log(e, '添加购物车失败');
            this.setData({
                toast: {
                    visible: true,
                    text: '加入购物车失败'
                }
            })
        }
    },

    // 获取购物车列表
    async getCartList() {
        let obj = {
            currenetPageIndex: 1,
            pageSize: 100
        }
        try {
            let res = await api.cart.getCartList(obj),
                data = res.data.ResData || {};
            this.setData({
                cartCount: data.Items.length || 0,
                status: 2
            })
            console.log(res, '购物车列表');

        } catch (e) {
            console.log(e, '获取购物侧列表失败')
        }
    },

    // 获取第一个不为0的规格index
    getActive() {
        let specs = this.data.pageData ? this.data.pageData.GoodsSpecDtos : [];

        // 统一处理价格
        specs.map(((item, index) => {
            if (this.data.source === 'goods') {
                item.goodsType = 'goods'
                item.price = item.Price
                item.lineationPrice = ''
            }

            if (this.data.source === 'kanjia') {
                item.goodsType = 'kanjia'
                item.price = this.data.kanjia.data.minimum_amount
                item.lineationPrice = this.data.kanjia.data.initial_amount
            }

            if (this.data.source === 'miaosha') {
                item.goodsType = 'miaosha'
                item.price = item.SeckillPric
                item.lineationPrice = item.Price
            }

            if (this.data.source === 'zaohui') {
                item.goodsType = 'zaohui'
                item.price = item.current_amount
                item.lineationPrice = '' // item.Price
            }

            if (this.data.source === 'pingtuan') {
                item.goodsType = 'pingtuan'
                item.price = item.collagePrice
                item.lineationPrice = '' // item.itemPrice
            }

            return item
        }))

        this.setData({
            ['pageData.GoodsSpecDtos']: specs
        })

        console.log('这里', specs)
       

        // 获取第一个库存不为0的数
        if (specs) {
            for (let i = 0; i < specs.length; i++) {
                if (specs[i].Stock != 0) {
                    this.setData({
                        active: i
                    });
                    break;
                }
            }
        }
    },

    // 显示分享弹框
    showShare() {
        this.setData({
            'share.visible': true
        });
    },

    // 获取评论区内容
    async get_evaluate() {
        // 获取评论总数和好评百分比 start
        let arr = {
            goods_id: this.data.id
        }
        let res = await api.goods.getGoodsEvaluateCount(arr)
        let count = res.data.ResData.count
        let billie = res.data.ResData.billie

        // 正式调用接口
        this.setData({
            evaluateArrCount: count,
            evaluateArrBillie: parseFloat(billie).toFixed(2)
        })

        // 测试写死数据
        // this.setData({
        //     evaluateArrCount: testdata.data.ResData.count,
        //     evaluateArrBillie: parseFloat(testdata.data.ResData.billie).toFixed(2)
        // })
        // end


        // // 获取最新一条评论作为展示
        let arr2 = {
            goods_id: this.data.id
        }
        let res2 = await api.goods.getGoodsEvaluate(arr2)
        let data2 = res2.data.ResData.Items
       

        // 正式调用接口
        this.setData({
          evaluateArr: data2.length === 0 ? [] : [data2[0]]
        })

        // 测试写死数据
        // this.setData({
        //     evaluateArr: [testdata.data2.ResData.Items[0]]
        // })
        // // end
    },

    // 打开评论区
    evaluate_tap() {
        wx.navigateTo({
            url: `/pages/product/evaluate/evaluate?goodsId=${this.data.id}`,
        })
    }
})